<?php
// 设置cookie参数，确保会话cookie正确设置 - 必须在session_start前设置
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 0); // 在HTTPS环境中设为1

// 确保先启动会话
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 加载通用文件
require_once __DIR__ . '/../common/autoload.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/../.installed')) {
    json_response(['success' => false, 'message' => '系统未安装'], 503);
}

// 设置调试模式（可以在生产环境设为false）
$debug_mode = true;

// 确保允许跨域请求（开发环境可能需要）
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('HTTP/1.1 200 OK');
    exit;
}

// 获取会话ID
$session_id = session_id();

// 如果session_id为空，重新生成
if (empty($session_id)) {
    session_regenerate_id();
    $session_id = session_id();
    if ($debug_mode) {
        error_log("会话ID为空，已重新生成: {$session_id}");
    }
}

// 测试模式：允许通过URL参数指定会话ID（仅用于测试）
if (isset($_GET['test_session']) && $debug_mode) {
    $test_session = $_GET['test_session'];
    error_log("使用测试会话ID: {$test_session}");
    $session_id = $test_session;
}

// 记录关键会话信息
if ($debug_mode) {
    $request_method = $_SERVER['REQUEST_METHOD'];
    $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '未设置';
    $raw_post = file_get_contents('php://input');
    
    error_log("Cart API 请求详情:");
    error_log("- 会话ID: {$session_id}");
    error_log("- 请求方法: {$request_method}");
    error_log("- Content-Type: {$content_type}");
    error_log("- POST原始数据: " . substr($raw_post, 0, 200) . (strlen($raw_post) > 200 ? '...' : ''));
    error_log("- GET参数: " . json_encode($_GET));
    error_log("- POST参数: " . json_encode($_POST));
}

// 处理不同的操作
$action = isset($_GET['action']) ? $_GET['action'] : '';

// 如果是POST请求，从JSON请求体中获取数据
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents('php://input');
    
    // 记录原始JSON数据（调试）
    if ($debug_mode) {
        error_log("原始JSON数据: " . $json_data);
    }
    
    // 尝试解析JSON
    $data = json_decode($json_data, true);
    
    // 检查JSON解析是否成功
    if (json_last_error() !== JSON_ERROR_NONE) {
        $error = json_last_error_msg();
        error_log("JSON解析错误: " . $error);
        json_response([
            'success' => false, 
            'message' => 'JSON解析错误: ' . $error,
            'error_code' => 'JSON_PARSE_ERROR',
            'raw_data' => substr($json_data, 0, 100) . (strlen($json_data) > 100 ? '...' : '')
        ], 400);
        exit;
    }
    
    if (isset($data['action'])) {
        $action = $data['action'];
    }
}

// 记录请求详情（调试用）
if ($debug_mode) {
    error_log("Cart API Request: action={$action}, method={$_SERVER['REQUEST_METHOD']}, session_id={$session_id}");
    if (isset($data)) {
        error_log("解析后的JSON数据: " . json_encode($data));
    }
}

try {
    switch ($action) {
        case 'get':
            // 获取购物车
            getCart($session_id);
            break;
        case 'add':
            // 添加商品到购物车
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            addToCart($session_id, $data);
            break;
        case 'update':
            // 更新购物车商品数量
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            updateCart($session_id, $data);
            break;
        case 'remove':
            // 移除购物车商品
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            removeFromCart($session_id, $data);
            break;
        case 'clear':
            // 清空购物车
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                json_response(['success' => false, 'message' => '请求方法不正确'], 405);
            }
            clearCart($session_id);
            break;
        case 'health':
            // 健康检查API，快速返回结果以检测API是否可用
            healthCheck();
            break;
        default:
            json_response(['success' => false, 'message' => '未知操作'], 400);
            break;
    }
} catch (Exception $e) {
    // 记录错误
    error_log("Cart API Error: " . $e->getMessage() . "\n" . $e->getTraceAsString());
    // 返回错误响应
    json_response(['success' => false, 'message' => '系统错误: ' . $e->getMessage()], 500);
}

/**
 * 获取购物车
 * @param string $session_id 会话ID
 */
function getCart($session_id) {
    global $debug_mode;
    
    try {
        if ($debug_mode) {
            error_log("获取购物车 - 会话ID: {$session_id}");
        }
        
        // 验证会话ID
        if (empty($session_id)) {
            error_log("购物车API错误: 会话ID为空");
            json_response([
                'success' => false, 
                'error_code' => 'SESSION_INVALID',
                'message' => '无效的会话ID'
            ], 400);
            return;
        }
        
        // 检查数据库连接
        if (!Database::isConnected()) {
            error_log("购物车API错误: 数据库连接失败");
            json_response([
                'success' => false, 
                'error_code' => 'DB_CONNECTION_FAILED',
                'message' => '数据库连接失败'
            ], 500);
            return;
        }
        
        // 查询购物车商品
        try {
            $sql = "SELECT c.*, p.name as product_name, p.price 
                    FROM cart_items c 
                    JOIN products p ON c.product_id = p.id 
                    WHERE c.session_id = ? 
                    ORDER BY c.created_at";
            $cart_items = Database::fetchAll($sql, [$session_id]);
        } catch (Exception $e) {
            error_log("购物车查询异常: " . $e->getMessage());
            json_response([
                'success' => false, 
                'error_code' => 'DB_QUERY_FAILED',
                'message' => '购物车查询失败: ' . $e->getMessage()
            ], 500);
            return;
        }
        
        // 检查查询是否成功
        if ($cart_items === false) {
            if ($debug_mode) {
                error_log("购物车查询失败");
            }
            json_response([
                'success' => false, 
                'error_code' => 'DB_QUERY_FAILED',
                'message' => '数据库查询失败'
            ], 500);
            return;
        }
        
        if ($debug_mode) {
            error_log("购物车查询结果: " . count($cart_items) . " 个商品");
        }
        
        // 计算总价
        $total_amount = 0;
        $total_count = 0;
        
        foreach ($cart_items as $item) {
            $total_amount += $item['price'] * $item['quantity'];
            $total_count += $item['quantity'];
        }
        
        // 返回成功结果，即使购物车为空
        json_response([
            'success' => true, 
            'items' => $cart_items,
            'total_amount' => $total_amount,
            'total_count' => $total_count,
            'session_id' => $session_id // 返回会话ID便于调试
        ]);
    } catch (Exception $e) {
        error_log("Get Cart Error: " . $e->getMessage() . "\n" . $e->getTraceAsString());
        json_response([
            'success' => false, 
            'error_code' => 'UNEXPECTED_ERROR',
            'message' => '获取购物车失败: ' . $e->getMessage()
        ], 500);
    }
}

/**
 * 添加商品到购物车
 * @param string $session_id 会话ID
 * @param array $data 请求数据
 */
function addToCart($session_id, $data) {
    global $debug_mode;
    
    // 验证会话ID
    if (empty($session_id)) {
        if ($debug_mode) {
            error_log("添加购物车错误: 会话ID为空");
        }
        json_response(['success' => false, 'message' => '会话无效，请刷新页面'], 400);
        return;
    }
    
    // 验证参数
    if (!isset($data['product_id']) || !isset($data['quantity'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $product_id = (int) $data['product_id'];
    $quantity = (int) $data['quantity'];
    
    if ($quantity <= 0) {
        json_response(['success' => false, 'message' => '数量必须大于0'], 400);
    }
    
    try {
        // 记录调试信息
        if ($debug_mode) {
            error_log("添加购物车 - 会话ID: {$session_id}, 商品ID: {$product_id}, 数量: {$quantity}");
        }
        
        // 查询商品
        $product = Database::fetch("SELECT * FROM products WHERE id = ?", [$product_id]);
        if (!$product) {
            json_response(['success' => false, 'message' => '商品不存在'], 404);
        }
        
        // 检查商品状态
        if ($product['status'] != 1) {
            json_response(['success' => false, 'message' => '商品已下架'], 400);
        }
        
        // 检查库存
        if ($product['stock'] !== null && $quantity > $product['stock']) {
            json_response(['success' => false, 'message' => '库存不足'], 400);
        }
        
        // 检查购物车中是否已有该商品
        $cart_item = Database::fetch("SELECT * FROM cart_items WHERE session_id = ? AND product_id = ?", [$session_id, $product_id]);
        
        if ($cart_item) {
            // 更新数量
            $new_quantity = $cart_item['quantity'] + $quantity;
            
            // 再次检查库存
            if ($product['stock'] !== null && $new_quantity > $product['stock']) {
                json_response(['success' => false, 'message' => '库存不足'], 400);
            }
            
            Database::update('cart_items', ['quantity' => $new_quantity], 'id = ?', [$cart_item['id']]);
            
            if ($debug_mode) {
                error_log("更新购物车项 - ID: {$cart_item['id']}, 新数量: {$new_quantity}");
            }
        } else {
            // 添加新商品
            $insert_id = Database::insert('cart_items', [
                'session_id' => $session_id,
                'product_id' => $product_id,
                'quantity' => $quantity,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            if ($debug_mode) {
                error_log("添加新购物车项 - ID: {$insert_id}");
            }
        }
        
        // 获取更新后的购物车
        getCart($session_id);
    } catch (Exception $e) {
        error_log("Add To Cart Error: " . $e->getMessage());
        json_response(['success' => false, 'message' => '添加到购物车失败: ' . $e->getMessage()], 500);
    }
}

/**
 * 更新购物车商品数量
 * @param string $session_id 会话ID
 * @param array $data 请求数据
 */
function updateCart($session_id, $data) {
    // 验证参数
    if (!isset($data['cart_item_id']) || !isset($data['quantity'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $cart_item_id = (int) $data['cart_item_id'];
    $quantity = (int) $data['quantity'];
    
    try {
        if ($quantity <= 0) {
            // 如果数量为0或负数，则移除商品
            Database::delete('cart_items', 'id = ? AND session_id = ?', [$cart_item_id, $session_id]);
            getCart($session_id);
            return;
        }
        
        // 查询购物车项
        $cart_item = Database::fetch("SELECT * FROM cart_items WHERE id = ? AND session_id = ?", [$cart_item_id, $session_id]);
        if (!$cart_item) {
            json_response(['success' => false, 'message' => '购物车项不存在'], 404);
        }
        
        // 查询商品
        $product = Database::fetch("SELECT * FROM products WHERE id = ?", [$cart_item['product_id']]);
        if (!$product) {
            json_response(['success' => false, 'message' => '商品不存在'], 404);
        }
        
        // 检查库存
        if ($product['stock'] !== null && $quantity > $product['stock']) {
            json_response(['success' => false, 'message' => '库存不足'], 400);
        }
        
        // 更新数量
        Database::update('cart_items', ['quantity' => $quantity], 'id = ?', [$cart_item_id]);
        
        // 获取更新后的购物车
        getCart($session_id);
    } catch (Exception $e) {
        error_log("Update Cart Error: " . $e->getMessage());
        json_response(['success' => false, 'message' => '更新购物车失败: ' . $e->getMessage()], 500);
    }
}

/**
 * 从购物车中移除商品
 * @param string $session_id 会话ID
 * @param array $data 请求数据
 */
function removeFromCart($session_id, $data) {
    // 验证参数
    if (!isset($data['cart_item_id'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $cart_item_id = (int) $data['cart_item_id'];
    
    try {
        // 查询购物车项
        $cart_item = Database::fetch("SELECT * FROM cart_items WHERE id = ? AND session_id = ?", [$cart_item_id, $session_id]);
        if (!$cart_item) {
            json_response(['success' => false, 'message' => '购物车项不存在'], 404);
        }
        
        // 删除购物车项
        Database::delete('cart_items', 'id = ?', [$cart_item_id]);
        
        // 获取更新后的购物车
        getCart($session_id);
    } catch (Exception $e) {
        error_log("Remove From Cart Error: " . $e->getMessage());
        json_response(['success' => false, 'message' => '从购物车移除失败: ' . $e->getMessage()], 500);
    }
}

/**
 * 清空购物车
 * @param string $session_id 会话ID
 */
function clearCart($session_id) {
    try {
        // 删除该会话的所有购物车项
        Database::delete('cart_items', 'session_id = ?', [$session_id]);
        
        // 返回空购物车
        json_response([
            'success' => true, 
            'items' => [],
            'total_amount' => 0,
            'total_count' => 0
        ]);
    } catch (Exception $e) {
        error_log("Clear Cart Error: " . $e->getMessage());
        json_response(['success' => false, 'message' => '清空购物车失败: ' . $e->getMessage()], 500);
    }
}

/**
 * 健康检查API
 * 用于前端快速检测购物车API是否可用
 */
function healthCheck() {
    try {
        // 进行简单的数据库检查
        $result = Database::query("SELECT 1");
        
        if ($result) {
            json_response([
                'success' => true,
                'status' => 'ok',
                'timestamp' => time(),
                'message' => '购物车服务正常'
            ], 200);
        } else {
            json_response([
                'success' => false,
                'status' => 'error',
                'timestamp' => time(),
                'message' => '数据库连接失败'
            ], 500);
        }
    } catch (Exception $e) {
        json_response([
            'success' => false,
            'status' => 'error',
            'timestamp' => time(),
            'message' => '健康检查失败: ' . $e->getMessage()
        ], 500);
    }
} 